#include <boost/typeof/typeof.hpp>
#include <boost/property_tree/xml_parser.hpp>

#include "log4cplus.h"
#include "config.h"

using namespace boost::property_tree;

ConfigParse &ConfigParse::GetInstance(const std::string &path)
{
    static ConfigParse instance(path);
    return instance;
}

ConfigParse::ConfigParse(const std::string &path)
{
    filePath_ = path;
    status_ = 0;
    delayTime_ = 15 * 60;
    rebootTime_ = 175;
    feedTime_ = 30;
    hardware_ = "K";
    Parse();
}

bool ConfigParse::Parse()
{
    ptree pt, root;
    int value;

    try {
        xml_parser::read_xml(filePath_, pt);
        root = pt.get_child("root");
    } catch (std::exception &e) {
        log_error_fmt("Parse root error: %s", e.what());
        return false;
    }

    try {
        BOOST_AUTO(child, root);
        for (BOOST_AUTO(pos, child.begin()); pos != child.end(); ++pos)
        {
            if (pos->first.compare("status") == 0) {
                value = atoi(pos->second.data().c_str());
                if (value == 1) {
                    status_ = value;
                }
            } else if (pos->first.compare("delayTime") == 0) {
                value = atoi(pos->second.data().c_str());
                if (value >= 0) {
                    delayTime_ = value;
                }
            } else if (pos->first.compare("rebootTime") == 0) {
                value = atoi(pos->second.data().c_str());
                if (value >= 1 && value <= 175) {
                    rebootTime_ = value;
                }
            } else if (pos->first.compare("feedTime") == 0) {
                value = atoi(pos->second.data().c_str());
                if (value >= 5 && value <= 50) {
                    feedTime_ = value;
                }
            } else if (pos->first.compare("hardware") == 0) {
                hardware_ = pos->second.data();
            }
        }
    } catch (std::exception &e) {
        log_error_fmt("Parse config error: %s", e.what());
    }

    log_info_fmt("Filename: %s", filePath_.c_str());
    log_info_fmt("Content: status[%d] delayTime[%d] rebootTime[%d] feedTime[%d] hardware[%s]",
                 status_, delayTime_, rebootTime_, feedTime_, hardware_.c_str());
    return true;
}

int ConfigParse::GetStatus() const
{
    return status_;
}

int ConfigParse::GetDelayTime() const
{
    return delayTime_;
}

int ConfigParse::GetRebootTime() const
{
    return rebootTime_;
}

int ConfigParse::GetFeedTime() const
{
    return feedTime_;
}

std::string ConfigParse::GetHardware() const
{
    return hardware_;
}
